package com.ruoyi.web.controller.article;

import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.article.domain.HsArticle;
import com.ruoyi.article.service.IHsArticleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.WordDocumentUtil;
import com.ruoyi.topic.service.IHsTopicService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

/**
 * 文章内容Controller
 * 
 * @author lzk
 * @date 2025-06-16
 */
@RestController
@RequestMapping("/article/article")
@Tag(name = "【文章内容】管理")
public class HsArticleController extends BaseController
{
    @Autowired
    private IHsArticleService hsArticleService;
    
    @Autowired
    private WordDocumentUtil wordDocumentUtil;

    @Autowired
    private IHsTopicService hsTopicService;

    /**
     * 查询文章内容列表
     */
    @Operation(summary = "查询文章内容列表")
    @PreAuthorize("@ss.hasPermi('article:article:list')")
    @GetMapping("/list")
    public TableDataInfo list(HsArticle hsArticle)
    {
        startPage();
        List<HsArticle> list = hsArticleService.selectHsArticleList(hsArticle);
        return getDataTable(list);
    }

    /**
     * 导出文章内容列表
     */
    @Operation(summary = "导出文章内容列表")
    @PreAuthorize("@ss.hasPermi('article:article:export')")
    @Log(title = "文章内容", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HsArticle hsArticle)
    {
        List<HsArticle> list = hsArticleService.selectHsArticleList(hsArticle);
        ExcelUtil<HsArticle> util = new ExcelUtil<HsArticle>(HsArticle.class);
        util.exportExcel(response, list, "文章内容数据");
    }

    /**
     * 获取文章内容详细信息
     */
    @Operation(summary = "获取文章内容详细信息")
    @PreAuthorize("@ss.hasPermi('article:article:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(hsArticleService.selectHsArticleById(id));
    }

    /**
     * 新增文章内容
     */
    @Operation(summary = "新增文章内容")
    @PreAuthorize("@ss.hasPermi('article:article:add')")
    @Log(title = "文章内容", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HsArticle hsArticle)
    {
        return toAjax(hsArticleService.insertHsArticle(hsArticle));
    }

    /**
     * 修改文章内容
     */
    @Operation(summary = "修改文章内容")
    @PreAuthorize("@ss.hasPermi('article:article:edit')")
    @Log(title = "文章内容", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HsArticle hsArticle)
    {
        return toAjax(hsArticleService.updateHsArticle(hsArticle));
    }

    /**
     * 删除文章内容
     */
    @Operation(summary = "删除文章内容")
    @PreAuthorize("@ss.hasPermi('article:article:remove')")
    @Log(title = "文章内容", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable( name = "ids" ) Long[] ids) 
    {
        return toAjax(hsArticleService.deleteHsArticleByIds(ids));
    }
    
    /**
     * 上传Word文档并解析
     */
    @Operation(summary = "上传Word文档并解析")
    @PreAuthorize("@ss.hasPermi('article:article:add')")
    @Log(title = "上传Word文档", businessType = BusinessType.INSERT)
    @PostMapping("/uploadWord")
    public AjaxResult uploadWordDocument(
            @RequestParam("file") MultipartFile file,
            @RequestParam("topicId") Long topicId,
            @RequestParam(value = "sourceUrl", required = false) String sourceUrl) 
    {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("请选择要上传的Word文档");
            }
            
            // 检查文件格式
            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.toLowerCase().endsWith(".doc") && !fileName.toLowerCase().endsWith(".docx"))) {
                return AjaxResult.error("请上传 .doc 或 .docx 格式的Word文档");
            }
            
            // 解析Word文档
            WordDocumentUtil.WordParseResult parseResult = wordDocumentUtil.parseWordDocument(file);
            
            if (!parseResult.isSuccess()) {
                return AjaxResult.error("文档解析失败: " + parseResult.getMessage());
            }
            
            // 创建文章对象
            HsArticle article = new HsArticle();
            article.setTopicId(topicId);
            article.setTitle(parseResult.getTitle());
            article.setContent(parseResult.getContent());
            if (sourceUrl != null && !sourceUrl.trim().isEmpty()) {
                article.setSourceUrl(sourceUrl.trim());
            } else {
                article.setSourceUrl(""); // 如果没有来源URL，设置为空字符串
            }
            
            // 保存到数据库
            int result = hsArticleService.insertHsArticle(article);
            
            if (result > 0) {
                return AjaxResult.success("Word文档解析并保存成功", article);
            } else {
                return AjaxResult.error("保存到数据库失败");
            }
            
        } catch (Exception e) {
            return AjaxResult.error("上传Word文档失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取下一个可用的topicId
     */
    @Operation(summary = "获取下一个可用的topicId")
    @PreAuthorize("@ss.hasPermi('article:article:add')")
    @GetMapping("/getNextTopicId")
    public AjaxResult getNextTopicId() 
    {
        try {
            // 获取所有topic，找到最大的ID
            List<com.ruoyi.topic.domain.HsTopic> topicList = hsTopicService.selectHsTopicList(new com.ruoyi.topic.domain.HsTopic());
            
            Long maxId = 0L;
            if (topicList != null && !topicList.isEmpty()) {
                for (com.ruoyi.topic.domain.HsTopic topic : topicList) {
                    if (topic.getId() != null && topic.getId() > maxId) {
                        maxId = topic.getId();
                    }
                }
            }
            
            // 返回下一个可用的ID
            return AjaxResult.success("获取成功", maxId + 1);
            
        } catch (Exception e) {
            return AjaxResult.error("获取topicId失败: " + e.getMessage());
        }
    }
}
